import { defineStore } from 'pinia';

export const useTabs = defineStore('tabs', {
    state: () => {
        return {
            // 存储当前打开的所有 Tabs 信息
            tabsList: [{ path: "/index", name: "首页" }],
            // 当前激活的 Tab 的唯一标识
            activeTab: null
        };
    },
    actions: {
        addTab(tab) {
            // 检查该 Tab 是否已经存在
            const existingTab = this.tabsList.find(t => t.path === tab.path);
            if (!existingTab) {
                this.tabsList.push(tab);
            }
            // 设置当前激活的 Tab
            this.activeTab = tab.path;
        },
        removeTab(tabPath) {
            const index = this.tabsList.findIndex(t => t.path === tabPath);
            if (index !== -1) {
                this.tabsList.splice(index, 1);
                // 如果删除的是当前激活的 Tab，需要更新 activeTab
                if (this.activeTab === tabPath) {
                    if (this.tabsList.length > 0) {
                        // 激活前一个 Tab
                        this.activeTab = this.tabsList[index === 0 ? 0 : index - 1].path;
                    } else {
                        this.activeTab = null;
                    }
                }
            }
        },
        setActiveTab(tabPath) {
            this.activeTab = tabPath;
        }
    },
    getters: {
        getActiveTabInfo() {
            return this.tabsList.find(t => t.path === this.activeTab) || null;
        }
    },
    persist: true
});